package main

import (
	logging "github.com/sirupsen/logrus"
	"webdemo/src/zinx/zinterface"
	"webdemo/src/zinx/znet"
)

/**
基于 zinx 框架开发的 服务器框架
*/

func main() {
	// 创建一个server,使用 Zinx 的 api
	server := znet.NewServer("zinx server")

	server.AddRouter(0, &PingRouter{})
	server.AddRouter(201, &PingRouter2{})
	// 注册hook函数
	server.SetOnConnStart(DoConnBegin)
	server.SetOnConnStop(DoConnStop)
	// 启动server
	server.Server()
}

func DoConnBegin(conn zinterface.IConnection) {
	logging.Info("[DoConnBegin]--begin-->")
	err := conn.SendMsg(2001, []byte("hook begin"))
	if err != nil {
		logging.Error("[DoConnBegin]error is ", err)
	}
	// 设置一些属性
	conn.SetProperty("Name", "jingzhongshuiyue")
	conn.SetProperty("Gitee", "https://gitee.com/moon-in-the-mirror/goweb")
}

func DoConnStop(conn zinterface.IConnection) {
	logging.Info("[DoConnStop]--end-->")

	if property, err := conn.GetProperty("Name"); err == nil {
		logging.Info("[DoConnStop]", property)
	}
	if property, err := conn.GetProperty("Gitee"); err == nil {
		logging.Info("[DoConnStop]", property)
	}
}

// 自定义路由
type PingRouter struct {
	znet.BaseRouter
}

// 重写 baseRouter 方法
/*func (this *PingRouter) PreHandle(request zinterface.IRequest) {
	_, err := request.GetConnection().GetTCPConnection().Write([]byte("preHandle..."))
	if err != nil {
		logging.Error("[server][PreHandle] error is ",err)
	}
}*/

func (this *PingRouter) Handle(request zinterface.IRequest) {

	logging.Info("[server][Handle] data is ", string(request.GetData()))

	err := request.GetConnection().SendMsg(1, []byte("ping..."))
	if err != nil {
		logging.Error("[server][Handle] SendMsg is ", err)
	}
}

/*func (this *PingRouter) PostHandle(request zinterface.IRequest) {
	_, err := request.GetConnection().GetTCPConnection().Write([]byte("PostHandle..."))
	if err != nil {
		logging.Error("[server][PostHandle] error is ",err)
	}
}*/

type PingRouter2 struct {
	znet.BaseRouter
}

func (this *PingRouter2) Handle(request zinterface.IRequest) {

	logging.Info("[server][Handle2] data is ", string(request.GetData()))

	err := request.GetConnection().SendMsg(201, []byte("ping2..."))
	if err != nil {
		logging.Error("[server][Handle2] SendMsg is ", err)
	}
}
